import configparser
from pathlib import Path
from datetime import datetime

CONFIG_PATH = Path("config.ini")

from typing import Optional

class TokenStore:
    def __init__(self, config_path: Path = CONFIG_PATH):
        self.config_path = config_path
        self.config = configparser.ConfigParser()
        if self.config_path.exists():
            self.config.read(self.config_path, encoding="utf-8")
        else:
            self.config["tokens"] = {"access_token": "", "refresh_token": "", "saved_at": ""}
            self.config["email"] = {"EMAIL_AUTH_CODE": "", "EMAIL_SENDER": "", "EMAIL_RECEIVER": ""}
            with open(self.config_path, "w", encoding="utf-8") as f:
                self.config.write(f)

    def get_tokens(self):
        access = self.config.get("tokens", "access_token", fallback="")
        refresh = self.config.get("tokens", "refresh_token", fallback="")
        return access, refresh

    def save_tokens(self, access_token: str, refresh_token: Optional[str]):
        if "tokens" not in self.config:
            self.config["tokens"] = {}
        self.config["tokens"]["access_token"] = access_token or ""
        if refresh_token is not None:
            self.config["tokens"]["refresh_token"] = refresh_token
        self.config["tokens"]["saved_at"] = datetime.utcnow().isoformat()
        with open(self.config_path, "w", encoding="utf-8") as f:
            self.config.write(f)

    def get_email_settings(self):
        code = self.config.get("email", "EMAIL_AUTH_CODE", fallback="")
        sender = self.config.get("email", "EMAIL_SENDER", fallback="")
        receiver = self.config.get("email", "EMAIL_RECEIVER", fallback="")
        return code, sender, receiver

    def get_email_receivers_list(self):
        """
        获取配置中的收件人列表，优先读取 EMAIL_RECEIVER_LIST（逗号分隔），
        若不存在则回退到单收件人 EMAIL_RECEIVER
        """
        lst = self.config.get("email", "EMAIL_RECEIVER_LIST", fallback="")
        if lst:
            items = [x.strip() for x in lst.split(",") if x.strip()]
            if items:
                return items
        single = self.config.get("email", "EMAIL_RECEIVER", fallback="")
        return [single] if single else []